<?php

?>
<div id="vwDialog" class="hidden"></div>
<script>


    function closeVwDialog() {
        Elm.vwDialog.dialog('close');
        resetButton();
    }




    function openVwDialog(id, onSubmit) {

        id = id || 0;
        onSubmit = onSubmit || function(){};

        htmlRequest(
            'views.php?vwForm',
            {id: id},

            function(data) {
                Elm.vwDialog.html(data);
                Elm.vwDialog.dialog('open');
                Elm.addVwForm.successCallback = onSubmit;
            },
            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );


    }








var TabsObject = function(parent) {
    var that = this;

    that.Tab = function(id) {
        var tab = this;

        tab.parent = that;
        tab.id = id || rndString(8)+'-tab';
        tab.LI = $('<li></li>');
        tab.A = $('<a data-toggle="tab" data-target="#'+tab.id+'"></a>').appendTo(tab.LI);
        tab.DIV = $('<div class="tab-pane" id="'+tab.id+'"></div>');

        tab.setTitle = function(title) { tab.A.html(title); return tab; };
        tab.setText = function(text) { tab.DIV.html(text); return tab; };

        tab.destroy = function() {
            tab.LI.remove();
            tab.DIV.remove();
            tab = false;
        };
    };


    that.parent = $(parent);
    that.UL = $('<ul class="nav nav-tabs">');
    that.DIV = $('<div class="tab-content">');
    that.id = rndString(8);
    that.plusId = that.id+'-li-plus';
    that.plusLI = $('<li id="'+that.plusId+'-li"></li>').html('<a data-toggle="tab" data-target="'+that.plusId+'"><i class="icon-plus"></i></a>');
    that.tabs = {};
    that.onAddTab = function(tab) {};

    that.LIs = [];




    that.init = function() {
        that.UL.attr({id: that.id+'-ul'}).appendTo(that.parent);
        that.DIV.attr({id: that.id+'-div'}).appendTo(that.parent);

        that.UL.append(that.plusLI);
        that.DIV.append('<div class="tab-pane" id="'+that.plusId+'">&nbsp;</div>');
        that.plusLI.find('a').on('show', function(){ that.onAddTab(); return false; });

        return that;
    };


    that.addTab = function (id, title, text) {
        id = id || false;
        title = title || '&nbsp;';
        text = text || '<p></p>';
        var t = new that.Tab(id);
        that.tabs[t.id] = t.setTitle(title).setText(text);
        that.appendLI(t.LI);
        t.DIV.appendTo(that.DIV);
        t.A.tab('show');
        that.LIsList();
        return t;
    };

    that.appendLI = function (li) {
        li.insertBefore(that.plusLI);
    }

    that.LIsList = function() {
        that.LIs = that.UL.children('li[id!="'+that.plusId+'-li"]');
        //alert('lis');
        return that.LIs;
    }



    that.removeTab = function (id) {
        that.tabs[id].destroy();
        that.tabs[id] = null;
        that.LIsList();
    };



};






var Floors = function(parent) {
    var fs = this;

    //fldata = fldata || {};
    //fs.refreshAction = 'VIEW_GET_FLOORS';

    fs.vwId = 0;
    //fs.items = (fldata.hasOwnProperty('floors') && fldata.floors) ? fldata.floors : [];
    fs.items = [];
    fs.itemsLen = 0; //fs.items.length;
    //fs.defaultFl = (fldata.hasOwnProperty('def_floor') && fldata.def_floor)? fldata.def_floor : 0;
    fs.defaultFl = 0;
    fs.parent = $(parent);


//....................................

    fs.Floor = function(data) {
        var fl = this;
        fl.flds = false;


        fl.setParams = function(data) {
            var def = {
                id: '',
                name: '',
                dss: [],
                view_order: 0
            };

            $.extend(def, data);
            if (!def.id) return;

            fl.id = def.id;// || rndString(8);
            fl.name = def.name;
            fl.view_order = def.view_order;
            fl.dss = def.dss;


        };

        fl.setParams(data);

        fl.tab = fs.tabs.addTab(fl.id, fl.name);//tabs[fl.id]; !!!!


        fl.buttons = {
            def: false,
            left: false,
            right: false,
            del: false
        };

        fl.tab.A.on('show', function () {
            fl.refresh();
        });






        fl.setTabTemplate = function() {
            var html = $('#addFloor-tmpl').html().gReplace('{%fl_id%}', fl.id).gReplace('{%fl_name%}', fl.name);
            fl.tab.setText(html);

            fl.buttons.def      = $('#def-'+fl.id);
            fl.buttons.left     = $('#left-'+fl.id);
            fl.buttons.right    = $('#right-'+fl.id);
            fl.buttons.del      = $('#del-'+fl.id);

            fl.TBODY = $('#srcTable-'+fl.id+' > tbody').empty();
            fl.flds = new DataSources(fl);


            fl.buttons.def.click(function (){
                fl.requestSetDefault();
                return false;
            });

            fl.buttons.left.click(function (){
                //fl.toLeft();///!!!!!!!
                fl.requestReOrder('left');
                return false;
            });

            fl.buttons.right.click(function (){
               // fl.toRight();///!!!!!!!
               fl.requestReOrder('right');
               return false;
            });


            fl.buttons.del.click(function (){
                fl.requestDelete();
                return false;
            });

            $('#fl_name-'+fl.id).change(function() {
                //fl.refresh();///!!!!!!!
                fl.requestNameUpdate();
            });
            var to;
             $('#fl_name-'+fl.id).keyup(function() {
                 if (to) clearTimeout(to);
                 to = setTimeout(function(){$('#fl_name-'+fl.id).change();}, 500);
             });

            $('#flAddSrc-open-'+fl.id).click(function() {
                // add ds

                var ds = fl.flds.getNewDs();

                FLDSFormOpen (ds, '<?php echo ACTIONS::VIEW_CREATE_VWFLDS; ?>');
                Elm.addFLDSForm.successCallback = function(newData) {
                    ds.setParams(newData);
                    fl.flds.appendDS(ds);
                    //ds.refreshTR();
                }
            });

        };



        fl.requestNameUpdate = function() {
            var send = {
                vw_id   : fs.vwId,
                id      : fl.id,
                name    : $('#fl_name-'+fl.id).val(),
                action  : '<?php echo ACTIONS::VIEW_FLOORS_UPDNAME; ?>'
            };

            jsonRequest(
                'views.php?flNameUpd',
                send,
                function(data) {
                    if(checkSession(data)) {
                        if (!data.state) {
                            uiAlert(data.message,'Error');
                            return;
                        }
                        if (!data.hasOwnProperty('response_data')) {
                            uiAlert('Ошибка данных','Error');
                            return;
                        }
                        var rdata = data.response_data;
                        if (rdata.hasOwnProperty('floor')) {
                            if (!rdata.floor.hasOwnProperty('id')) {
                                uiAlert('Ошибка данных','Error');
                                return;
                            }
                            if (rdata.floor.id != fl.id) {
                                uiAlert('Ошибка данных','Error');
                                return;
                            }

                            fl.setParams(rdata.floor);
                            fl.refresh();
                        }
                    }
                    else {
                        Elm.loginFormModal.dialog('open');
                        Elm.loginFormModal.successCallback = function(){
                            fl.requestNameUpdate();
                        };
                        return;
                    }
                },
                function() { uiAlert('Ошибка соединения','Error'); }
            );
        };


        fl.requestSetDefault = function() {
            var send = {
                vw_id   : fs.vwId,
                id      : fl.id,
                action  : '<?php echo ACTIONS::VIEW_UPDATE_DEF; ?>'
            };
            
            jsonRequest(
                'views.php?flSetDef',
                send,
                function(data) {
                    if(checkSession(data)) {
                        if (!data.state) {
                            uiAlert(data.message,'Error');
                            return;
                        }
                        if (!data.hasOwnProperty('response_data')) {
                            uiAlert('Ошибка данных','Error');
                            return;
                        }
                        var rdata = data.response_data;
                        if (rdata.hasOwnProperty('result') && rdata.result) {
                            fs.setDefault(fl.id);
                        }
                        else uiAlert('Действие не произведено, попробуйте ещё раз.','Error');
                    }
                    else {
                        Elm.loginFormModal.dialog('open');
                        Elm.loginFormModal.successCallback = function(){
                            fl.requestSetDefault();
                        };
                        return;
                    }
                },
                function() { uiAlert('Ошибка соединения','Error'); }
            );
        };




        fl.requestDelete = function() {
            uiConfirm({
                title : 'Подтверждение',
                text :  'Удалить срез данных "'+fl.name+'"?',
                ok :    function(){ 
                    var send = {
                        vw_id   : fs.vwId,
                        id      : fl.id,
                        action  : '<?php echo ACTIONS::VIEW_DELETE_VWFLOOR; ?>'
                    };

                    jsonRequest(
                        'views.php?flDelete',
                        send,
                        function(data) {
                            if(checkSession(data)) {
                                if (!data.state) {
                                    uiAlert(data.message,'Error');
                                    return;
                                }
                                if (!data.hasOwnProperty('response_data')) {
                                    uiAlert('Ошибка данных','Error');
                                    return;
                                }
                                var rdata = data.response_data;
                                if (rdata.hasOwnProperty('result') && rdata.result) {
                                    fs.removeFloor(fl.id);
                                }
                                else uiAlert('Действие не произведено, попробуйте ещё раз.','Error');
                            }
                            else {
                                Elm.loginFormModal.dialog('open');
                                Elm.loginFormModal.successCallback = function(){
                                    fl.requestDelete();
                                };
                                return;
                            }
                        },
                        function() { uiAlert('Ошибка соединения','Error'); }
                    );
                },
                cancel: function(){}
            });
                    
            return false;
        };


        fl.requestReOrder = function(dir) {
            var send = {
                vw_id   : fs.vwId,
                id      : fl.id,
                dir     : dir,
                action  : '<?php echo ACTIONS::VIEW_FLOORS_UPDORDER; ?>'
            };

            jsonRequest(
                'views.php?flOrder',
                send,
                function(data) {
                    if(checkSession(data)) {
                        if (!data.state) {
                            uiAlert(data.message,'Error');
                            return;
                        }
                        if (!data.hasOwnProperty('response_data')) {
                            uiAlert('Ошибка данных','Error');
                            return;
                        }
                        var rdata = data.response_data;
                        if (rdata.hasOwnProperty('result') && rdata.result) {
                            fs.refresh();
                        }
                        else uiAlert('Действие не произведено, попробуйте ещё раз.','Error');
                    }
                    else {
                        Elm.loginFormModal.dialog('open');
                        Elm.loginFormModal.successCallback = function(){
                            fl.requestDelete();
                        };
                        return;
                    }
                },
                function() { uiAlert('Ошибка соединения','Error'); }
            );
        };


        fl.refresh = function () {
            //alert('fl.ref');
            if (fs.defaultFl == fl.id) fl.buttons.def.addClass('btn-info');
            else fl.buttons.def.removeClass('btn-info');

            $('#fl_name-'+fl.id).val(fl.name);
            fl.tab.setTitle(fl.name+'&nbsp;');

            var lis = fs.tabs.LIs;

            if (lis.get(0) == fl.tab.LI.get(0)) fl.buttons.left.attr('disabled','disabled');
            else fl.buttons.left.removeAttr('disabled');

            if (lis.get(lis.length-1) == fl.tab.LI.get(0)) fl.buttons.right.attr('disabled','disabled');
            else fl.buttons.right.removeAttr('disabled');

            lis.removeClass('info');
            if (fs.tabs.tabs.hasOwnProperty(fs.defaultFl) && fs.tabs.tabs[fs.defaultFl]) fs.tabs.tabs[fs.defaultFl].LI.addClass('info');

            fl.flds.loadFromArray(fl.dss);
        };



        fl.toLeft = function () {
            var lis = fs.tabs.LIs;
            var li = fl.tab.LI.get(0);
            if (lis.get(0) == li) return;
            var vo = fl.view_order;
            var prev = false;
            for(var i in fs.items) {
                if (!fs.items.hasOwnProperty(i)) continue;
                if (!fs.items[i]) continue;
                if (fs.items[i].view_order*1 == vo*1-1) {
                    fs.items[i].view_order++;
                    fl.view_order--;
                    fl.tab.LI.insertBefore(fs.items[i].tab.LI);
                    fs.tabs.LIsList();
                    fl.refresh();
                    break;
                }
            }

        };


        fl.toRight = function () {
            var lis = fs.tabs.LIs;
            var li = fl.tab.LI.get(0);
            if (lis.get(lis.length-1) == li) return;
            var vo = fl.view_order;
            var next = false;
            for(var i in fs.items) {
                if (!fs.items.hasOwnProperty(i)) continue;
                if (!fs.items[i]) continue;
                if (fs.items[i].view_order*1 == vo*1+1) {
                    fs.items[i].view_order--;
                    fl.view_order++;
                    fs.items[i].tab.LI.insertBefore(fl.tab.LI);
                    fs.tabs.LIsList();
                    fl.refresh();
                    break;
                }
            }

        };

    }


    fs.requestFlCreate = function() {
        var send = {
            vw_id   : fs.vwId,
            action  : '<?php echo ACTIONS::VIEW_CREATE_VWFLOOR; ?>'
        };

        jsonRequest(
            'views.php?flCreate',
            send,
            function(data) {
                if(checkSession(data)) {
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        return;
                    }
                    if (!data.hasOwnProperty('response_data')) {
                        uiAlert('Ошибка данных','Error');
                        return;
                    }
                    var rdata = data.response_data;
                    if (rdata.hasOwnProperty('floor')) {
                        if (!rdata.floor.hasOwnProperty('id')) {
                            uiAlert('Ошибка данных','Error');
                            return;
                        }
                        if (!rdata.floor.id ) {
                            uiAlert('Ошибка данных','Error');
                            return;
                        }
                        fs.addFloor(rdata.floor);
                        //fl.setParams(rdata.floor);
                        //fl.refresh();
                    }
                }
                else {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){
                        fs.requestFlCreate();
                    };
                    return;
                }
            },
            function() { uiAlert('Ошибка соединения','Error'); }
        );
    };



    fs.setDefault = function(id) {
        if (!fs.items.hasOwnProperty(id)) return;
        var fl = fs.items[id];
        fs.defaultFl = id; ///!!!!!!!
        setTimeout(function() {fl.refresh();}, 300);
    }

    fs.addFloor = function(fldata) {
        fldata = fldata || false;
        if (!fldata || !fldata.hasOwnProperty('id') || !fldata.id) return;

        var fl = new fs.Floor(fldata);
        fs.items[fldata.id] = fl;
        fs.itemsLen++;
        fl.setTabTemplate();
        fl.refresh();
        if (!fs.defaultFl || !fs.items.hasOwnProperty(fs.defaultFl) || !fs.items[fs.defaultFl]) fl.requestSetDefault();
    };


    fs.removeFloor = function(id) {
        var fl = fs.items[id];
        var vo = fl.view_order;

        for(var i in fs.items) {
           if (!fs.items.hasOwnProperty(i)) continue;
           if (fs.items[i] && fs.items[i].view_order>vo) fs.items[i].view_order--;
        }

        fs.items[id] = null;
        fs.tabs.removeTab(id);
        fs.itemsLen--;

        var lis = fs.tabs.LIs;
        if (!lis.filter('.active').length) {
            $(lis.get(0)).find('a').tab('show');
        }
    };





    fs.refresh = function() {

        var send = {
            vw_id   : fs.vwId,
            action  : '<?php echo ACTIONS::VIEW_FLOORS_GET; ?>'
        };

        jsonRequest(
            'views.php?refreshFs',
            send,
            function(data) {
                if(checkSession(data)) {
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        return;
                    }

                    if (!data.hasOwnProperty('response_data')) return;
                    var rdata = data.response_data;

                    if (rdata.hasOwnProperty('floors')) {
                        var floors = rdata.floors;
                        var newItems = [];
                        for(var i in fs.items) {
                            if (!fs.items.hasOwnProperty(i)) continue;
                            if (!fs.items[i]) continue;

                            var inArr = false;
                            for (var j in floors) {
                                if (!floors.hasOwnProperty(j)) continue;
                                if (floors[j].hasOwnProperty('id') && floors[j].id == i) {
                                    inArr = true;
                                    break;
                                }
                            }
                            if (inArr) {
                                fs.items[i].tab.LI.detach();
                                newItems[i] = fs.items[i];
                            }
                            else fs.removeFloor(i);

                            /*
                            if (floors.hasOwnProperty(i)) {
                                fs.items[i].tab.LI.detach();
                                newItems[i] = fs.items[i];
                            }
                            else fs.removeFloor(i);
                            */
                        }
                        fs.items = newItems;


                        for (var i in floors) {
                            if (!floors.hasOwnProperty(i)) continue;

                            if (fs.items.hasOwnProperty(floors[i].id)) {
                                fs.items[floors[i].id].setParams(floors[i]);
                                fs.tabs.appendLI(fs.items[floors[i].id].tab.LI);
                                //fs.items[i].refresh();
                            }
                            else fs.addFloor(floors[i]);
                        }

                    }
                    fs.tabs.LIsList();
                    if (rdata.hasOwnProperty('view')) {
                        if (rdata.view.hasOwnProperty('def_floor')) {
                            if (fs.items.hasOwnProperty(rdata.view.def_floor) && fs.items[rdata.view.def_floor]) {
                                fs.setDefault(rdata.view.def_floor);
                            }
                        }
                    }
                    // Обновляем вкладки - вдруг имена поменялись?
                    for(var i in fs.items) {
                            if (!fs.items.hasOwnProperty(i)) continue;
                            if (!fs.items[i]) continue;
                            fs.items[i].refresh();
                    }
                }
                else {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){
                        fs.refresh();
                    };
                    return;
                }
            },

            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
    }





    fs.init = function() {
        fs.tabs = new TabsObject(fs.parent);
        fs.tabs.onAddTab = function(tab) {
            if(fs.vwId*1 < 1) {
                uiAlert('Необходимо сохранить данные отображения, прежде чем добавлять срезы данных','Информация');
                return false;
            }
            fs.requestFlCreate();
        };


        fs.refresh();

        fs.tabs.init();
    }
}









var DataSources = function(floor) {
    var ss = this;
    ss.TBODY = floor.TBODY;
    ss.floor = floor;

    ss.items = [];


    ss.DataSource = function(params) {
        var ds = this;

        params = params || {};

        ds.from = ss;
        ds.p = {
            id  : 0,
            floor_id : ss.floor.id,
            tbl : '',
            sen : '',
            use_timelimit : 0,
            time_min : '',
            time_max : '',
            time_shift : 0,
            whatsum : ''
        };



        ds.TR = false;
        ds.tds = {};
        ds.ctrls = {};


        ds.setParams = function (params) {
            params = params || {};
            $.extend(ds.p, params);
        };



        ds.loadTmpl = function() {
            var html = $('#flDsTr-tmpl').html().gReplace('{%flds_id%}', ds.p.id);
            var tempdiv = $('<table class="hidden">'+html+'</table>').appendTo('body');

            ds.TR = tempdiv.find('tr')

            ds.tds = {
                tbl     : $('#td-flds-tbl-'+ds.p.id),
                whatsum : $('#td-flds-whatsum-'+ds.p.id),
                sen     : $('#td-flds-sen-'+ds.p.id),
                interval: $('#td-flds-interval-'+ds.p.id)

            };

            ds.ctrls = {
                edit    : $('#btn-flds-edit-'+ds.p.id),
                del     : $('#btn-flds-del-'+ds.p.id)
            };


            ds.ctrls.edit.click(function() {
                // edit ds
                FLDSFormOpen (ds, '<?php echo ACTIONS::VIEW_UPDATE_VWFLDS; ?>');
                Elm.addFLDSForm.successCallback = function(newData) {
                    ds.setParams(newData);
                    ds.refreshTR();
                }
            });

            ds.ctrls.del.click(function() {
                // del ds
                uiConfirm({
                    title : 'Подтверждение',
                    text :  'Удалить источник данных?',
                    ok :    function(){ 
                        var send = {
                            action  : '<?php echo ACTIONS::VIEW_DELETE_VWFLDS; ?>',
                            id   : ds.p.id
                        };

                        jsonRequest(
                            'views.php?delFlds',
                            send,

                            function(data) {
                                if(checkSession(data)) {
                                    if (!data.state) {
                                        uiAlert(data.message,'Error');
                                        return;
                                    }

                                    if (data.hasOwnProperty('response_data') && data.response_data) {
                                        var resp = data.response_data;

                                        if (resp.hasOwnProperty('result') && resp.result) {
                                            ds.from.deleteDS(ds.p.id);
                                        }
                                    }
                                }
                                else {
                                    Elm.loginFormModal.dialog('open');
                                    Elm.loginFormModal.successCallback = function(){
                                        ds.ctrls.del.click();
                                    };
                                }
                            },

                            function() {
                                uiAlert('Ошибка соединения','Error');
                            }
                        );
                    },
                    cancel: function(){}
                });
                    

            });

            ds.TR.detach();
            tempdiv.remove();
            tempdiv = null;
        };


        ds.refreshTR = function() {
            ds.tds.tbl.html(ds.p.tbl);
            ds.tds.sen.html(ds.p.sen);
            if (ds.p.sen.gReplace(' ','')) {
                //ds.tds.sen.html(ds.p.sen.gReplace(',',', '));
            }
            else {
                ds.tds.sen.html('Все');
            }


            ds.tds.whatsum.html(ds.p.whatsum);

            if (ds.p.use_timelimit*1<1) ds.tds.interval.html('Круглосуточно');
            else ds.tds.interval.html(ds.p.time_min+' - '+ds.p.time_max);
        };

        ds.init = function() {
            ds.setParams(params);
            ds.loadTmpl();
            ds.refreshTR();
        };
    };


    ss.loadFromArray = function(dsarr) {
        dsarr = dsarr || [];

        ss.items = [];
        ss.TBODY.empty();

        for (var i in dsarr) {
            if (!dsarr.hasOwnProperty(i)) continue;

            var ds = dsarr[i];
            if (!(ds.hasOwnProperty('id') && ds.id)) continue;
            ds = new ss.DataSource(ds);
            ss.appendDS(ds);
        }

    }

    ss.deleteDS = function(id) {
        if (!(ss.items.hasOwnProperty(id) && ss.items[id])) return;
        ss.items[id].TR.remove();
        if (ss.floor.dss.hasOwnProperty(id)) delete(ss.floor.dss[id]);
        delete(ss.items[id]);

    };

    ss.getNewDs = function() {
        return new ss.DataSource({});
    };

    ss.appendDS = function(ds) {
        ds.init();
        ss.items[ds.p.id] = ds;
        ss.TBODY.append(ds.TR);
        if (!ss.floor.dss.hasOwnProperty(ds.p.id)) ss.floor.dss[ds.p.id] = ds.p;
    };



}




$(function() {

    Elm.vwDialog = $('#vwDialog');

    Elm.vwDialog.dialog({
        width       : 800,
        modal       : true,
        resizable   : false,
        title       : "Отображение",
        autoOpen    : false,
        zIndex      : 20000,
        buttons     : {}
    });
    Elm.vwDialog.removeClass('hidden');
    Elm.vwDialog.dialog('widget').find('a.ui-dialog-titlebar-close').hide();



});







</script>